#ifndef __COMM_HPP__
#define __COMM_HPP__


#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <string>
#include <cstring>
#include <cstdlib>
#include <stdio.h>

#include "log.hpp"
using namespace std;
const int id = 0xfffff;
const string pathname = "/home/zpb";
Log log;

enum
{
    MKFIFO_CREATE_ERR = 1,
    MKFIFO_OPEN_ERR,
    MKFIFO_UNLINK_ERR,
    FIFO_DELETE_ERR
};
class Init
{
public:
    Init()
    {
        int n = mkfifo("mkfifo", 0666);
        if (n == -1)
        {
            perror("makfifo");
            exit(MKFIFO_CREATE_ERR);
        }
    }

    ~Init()
    {
        int m = unlink("mkfifo");
        if (m == -1)
        {
            perror("unlink");
            exit(FIFO_DELETE_ERR);
        }
    }

};

int Getkey()
{
    key_t key = ftok(pathname.c_str(), id);
    if(key == -1)
    {
        //log(Fatal, "ftok error:%s", strerror(errno));
        exit(1);
    }
    cout << "用户约定的key:" << key << endl;
    return key;
}

int GetShmHelper(int flag)
{
    key_t key = Getkey();
    int shmid = shmget(key, 4096, flag);
    if(shmid == -1)
    {
        //log(Fatal, "shmget fail:%s", strerror(errno));
        exit(2);
    }
    cout << shmid << endl;
    //log(Info, "shmid success, shmid:%d", shmid);
    return shmid;
}

int CreateShm()
{
    return GetShmHelper(IPC_CREAT|IPC_EXCL|0666);
}

int GetShm()
{
    return GetShmHelper(IPC_CREAT|0666);
}
#endif
